package com.booktrading.controller;

import com.booktrading.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {

    @Value("${file.upload.dir}")
    private String fileUploadDir;

    /**
     * 上传文件
     * @param file 文件
     * @return 响应
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择要上传的文件");
            return ResponseEntity.ok(result);
        }
        
        try {
            String fileUrl = FileUploadUtil.saveFile(file, fileUploadDir);
            
            result.put("success", true);
            result.put("message", "上传成功");
            result.put("fileUrl", fileUrl);
            
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 从本地路径上传文件
     * @param localFilePath 本地文件路径
     * @return 响应
     */
    @PostMapping("/upload-from-local")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadFromLocalPath(@RequestParam("path") String localFilePath) {
        Map<String, Object> result = new HashMap<>();
        
        if (localFilePath == null || localFilePath.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "请提供本地文件路径");
            return ResponseEntity.ok(result);
        }
        
        try {
            String fileUrl = FileUploadUtil.saveFileFromLocalPath(localFilePath, fileUploadDir);
            
            result.put("success", true);
            result.put("message", "上传成功");
            result.put("fileUrl", fileUrl);
            
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
} 